// ignore_for_file: file_names, slash_for_doc_comments, must_call_super, unnecessary_overrides, override_on_non_overriding_member, must_be_immutable, prefer_const_constructors, sized_box_for_whitespace, avoid_unnecessary_containers, avoid_print

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mybase/base/super/FFInk.dart';
import 'package:mybase/base/tool/color/FFColor.dart';
import 'package:mybase/base/tool/empty/FFEmpty.dart';
import 'package:mybase/base/widget/layout/FFBranch.dart';
import 'package:mybase/base/widget/layout/FFImageButton.dart';

/**
 * 输入框 未适配所有情况
 */

class FFTextField extends StatefulWidget {
  /**
   * 实时回调
   * valid:输入框内容是否有效
   * value:输入框内容
   */
  Function(bool valid, String value) onValid;

  /**
   * 点击done search时回调
   */
  Function(String value)? onSubmitted;

  //最短位数
  int min;

  //最长位数
  int max;

  //高度，不带w
  double? height;

  //默认文字
  String placeStr;

  //文本对齐方式
  TextAlign? textAlign;

  //placeStr文本样式
  TextStyle? placeTextStyle;

  //自动进入焦点
  bool? autofocus;

  //焦点时文本样式
  TextStyle? focusTextStyle;

  //光标颜色 ,默认白色
  Color? cursorColor;

  // 默认输入的内容
  String? defalultText;

  // 键盘类型
  TextInputType? keyboardType;

  //done search
  TextInputAction? textInputAction;

  //是否需要取消按扭，默认true,需要
  bool? needCancelBtn;

  //额外添加的 输入限制,比如
  /**
      [
      LengthLimitingTextInputFormatter(widget.max),
      FilteringTextInputFormatter.allow(
      RegExp('[0-9xX]'),
      ),
      FilteringTextInputFormatter.deny()
      ]
   */
  List<TextInputFormatter>? inputFormatters;

  TextEditingController? controller;
  FocusNode? focusNode;

  FFTextField({
    Key? key,
    required this.onValid,
    required this.min,
    required this.max,
    this.height = 38,
    this.placeStr = '请输入内容',
    this.textAlign,
    this.defalultText,
    this.controller,
    this.cursorColor = Colors.white,
    this.inputFormatters,
    this.needCancelBtn = true,
    this.focusNode,
    this.textInputAction = TextInputAction.done,
    this.onSubmitted,
    this.autofocus = false,
    this.focusTextStyle,
    this.placeTextStyle,
    this.keyboardType = TextInputType.emailAddress,
  }) : super(key: key);

  @override
  State<FFTextField> createState() => _FFTextFieldState();
}

class _FFTextFieldState extends State<FFTextField> {
  late TextEditingController controller;
  late FocusNode focusNode;

  @override
  void initState() {
    super.initState();
    controller = widget.controller ?? TextEditingController(text: widget.defalultText);
    focusNode = widget.focusNode ?? FocusNode();

    if (widget.autofocus == true){
      Future.delayed(Duration(milliseconds: 300),(){
        if (mounted) {
          focusNode.requestFocus();
        }
      });
    }

    // 添加输入框焦点事件的捕捉和监听
    focusNode.addListener(() {
      if (focusNode.hasFocus) {
        // 获取焦点
      } else {
        // 失去焦点，去掉右侧清空按钮

      }
      setState(() {});
    });

    // if (!FFEmpty.stringIsEmpty(widget.defalultText)) {
    //   controller.text = widget.defalultText!;
    // }

    widget.inputFormatters ??= [LengthLimitingTextInputFormatter(widget.max)];
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: GestureDetector(
        onTap: () {
          focusNode.requestFocus();
        },
        child: Container(
          alignment: Alignment.center,
          height: widget.height!,
          child: Row(
            children: [
              Expanded(
                child: TextField(
                  cursorColor: widget.cursorColor,
                  keyboardType: widget.keyboardType,
                  inputFormatters: widget.inputFormatters,
                  controller: controller,
                  focusNode: focusNode,
                  maxLines: 1,
                  textAlign:widget.textAlign??TextAlign.start,
                  autofocus: widget.autofocus ?? false,
                  style: widget.focusTextStyle ??
                      TextStyle(fontSize: 16, color: Colors.white),
                  decoration: InputDecoration.collapsed(
                    hintText: widget.placeStr,
                    hintStyle: widget.placeTextStyle ??
                        TextStyle(
                            fontSize: 16,
                            color: Color.fromRGBO(114, 121, 112, 1)),
                  ),
                  onChanged: (value) {
                    checkValid();
                    setState(() {});
                  },
                  onSubmitted: widget.onSubmitted,
                  textInputAction: widget.textInputAction,
                ),
              ),
              // 未激活状态时，不需要显示删除按钮
              (FFEmpty.stringIsEmpty(controller.text) || !focusNode.hasFocus)
                  ? SizedBox()
                  : FFBranch(
                      condition: widget.needCancelBtn == true,
                      trueWidget: FFInk(
                        child: FFImageButton(
                          padding: EdgeInsets.symmetric(horizontal: 12),
                          image: FFImageFactory.asset(
                              "assets/images/navi/cancel.png"),
                          width: 40,
                          heigth: 40,
                          onClick: () {
                            controller.text = "";
                            checkValid();
                            setState(() {});
                          },
                        ),
                      )),
            ],
          ),
        ),
      ),
    );
  }

  /**
   * 实时检查
   */
  checkValid() {
    bool valid = false;

    if (!FFEmpty.stringIsEmpty(controller.text)) {
      if (controller.text.length >= widget.min &&
          controller.text.length <= widget.max) {
        valid = true;
      }
    }

    widget.onValid(valid, controller.text);
  }
}
